/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package com.icerhe.trigger;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.icerhe.trigger.task.AirplaneModeTaskSetting;
import com.icerhe.trigger.task.AlarmTaskSetting;
import com.icerhe.trigger.task.CronTask;
import com.icerhe.trigger.task.Task;
import com.icerhe.trigger.task.WifiTaskSetting;

/**
 * @author icer
 * 
 * 客户端主画面
 *
 */
public class ListActivity extends Activity {
	
	private static final String PREFS = "com.icerhe.trigger";
	
	private static final int TASK_SWITCH  = 0; //启动/停止任务
	private static final int TASK_MODIFY  = 1; //修改任务
	private static final int TASK_DELETE  = 2; //删除任务
	private static final int TASK_TESTRUN = 3; //测试执行任务
	
	private static final int ALARM_TASK   = 0; //定时提醒
	private static final int AIRPLANE_TASK = 1; //定时飞行模式 
	private static final int WIFI_TASK = 2; //定时飞行模式 
	
	private SharedPreferences prefs;
	private TaskListAdapter adapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)  {

    	super.onCreate(savedInstanceState);
        Log.d(Consts.TAG, "ListActivity create");
        //初始化主画面
        show();
        prefs = getSharedPreferences(PREFS, MODE_PRIVATE);
        getSystemService(Context.TELEPHONY_SERVICE);
       
    }
    
	@Override
	protected void onStart() {
		super.onStart();
		Log.d(Consts.TAG, "ListActivity start");
		refresh();
	}

    /*
     * 显示界面
     */
    private void show()  {

    	setContentView(R.layout.task_list);  	
    	//添加Task
    	View addTask = findViewById(R.id.add_task);
    	addTask.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				addNewTask();
			}
		});
    	
    	//任务列表
        final ListView list = (ListView) findViewById(R.id.task_list);
        adapter = new TaskListAdapter(this);
        list.setAdapter(adapter);         
        list.setOnItemClickListener(new OnItemClickListener(){
        	/** 点击task时显示弹出菜单   */
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {		
				showDialog(position);
			}
        });

    }
    
    private static final Handler handler = new Handler();
    private void refresh() {
    	handler.post(new Runnable() {
			@Override
			public void run() {
				adapter.notifyDataSetChanged();
			}
		});
    }
    
    /**
     * 添加新任务
     */
    private void addNewTask() {
    	new AlertDialog.Builder(this)
    		.setTitle(R.string.add_task)
    		.setItems(R.array.task_type_items, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch(which) {
					case ALARM_TASK:
						startActivity(new Intent(ListActivity.this, AlarmTaskSetting.class));
						break;
					case AIRPLANE_TASK:
						startActivity(new Intent(ListActivity.this, AirplaneModeTaskSetting.class));
						break;
					case WIFI_TASK:
						startActivity(new Intent(ListActivity.this, WifiTaskSetting.class));
						break;
					//TODO 这里以后加入新的task类型
					}
					
				}
			})
    		.show();
    }
    
    @Override
	protected Dialog onCreateDialog(int position) {
		
		final CronTask task = 
			TaskHelper.getAllCronTask(ListActivity.this).get(position);
		
		return new AlertDialog.Builder(ListActivity.this)
					.setTitle(task.getTitle())
					.setItems(R.array.task_operate_dialog_items, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int which) {
	                    	switch (which) {
                    		case TASK_MODIFY:
                    			Intent setting = new Intent(ListActivity.this, TaskHelper.getSettingClass(task));
                    			setting.putExtra(CronTask.INTENT_TASK_ID, task.getId());
                    			startActivity(setting);
                    			break;
                    		case TASK_DELETE:
                    			new AlertDialog.Builder(ListActivity.this)
                					.setMessage(R.string.delete_task_confirm)
                					.setPositiveButton(R.string.label_yes,
                						new DialogInterface.OnClickListener() {				
											@Override
											public void onClick(DialogInterface dialog, int id) {
												TaskHelper.deleteTask(ListActivity.this, task.id);
												refresh();
										}
									})
									.setNegativeButton(R.string.label_no, null)
									.show();
                    			break;
                    		case TASK_SWITCH:
                    			task.setEnabled(!task.isEnabled());
                    			TaskHelper.updateTask(ListActivity.this, task);
                    			refresh();
                    			break;
                    		case TASK_TESTRUN:
                    			task.runTask(ListActivity.this);
                    			break;
                    		default :
                    			String[] items = getResources().getStringArray(R.array.task_operate_dialog_items);
    	                        new AlertDialog.Builder(ListActivity.this)
    	                                .setMessage("You selected: " + which + " , " + items[which])
    	                                .show();	
	                    	}
	                        
	                    }
					})
					.create();
	}

	private static final int PERFERENCES = 1;
	private static final int ABOUT = 2;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
        menu.add(0, PERFERENCES, 1, R.string.menu_preferences);
        menu.add(0, ABOUT,       2, R.string.menu_about);
		return true;
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case PERFERENCES:
                //startActivity(new Intent(this, SetAlarm.class));
                return true;
            case ABOUT:
                //startActivity(new Intent(DOCK_SETTINGS_ACTION));
                return true;
            default:
                return false;
        }
    }
	
	
	/**
	 * Task列表适配器
	 * @author icer
	 *
	 */
	public class TaskListAdapter extends BaseAdapter {

		private LayoutInflater viewInflater;

		public TaskListAdapter(Context context) {
			viewInflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			
			final CronTask task = 
				TaskHelper.getAllCronTask(ListActivity.this).get(position);
			
			if (null == convertView) {				
				//填充视图
				convertView = viewInflater.inflate(R.layout.task_list_item, null);				
				holder = new ViewHolder();
				holder.title = (TextView)convertView.findViewById(R.id.TaskTitle);
				holder.summary=(TextView)convertView.findViewById(R.id.TaskSummary);
				holder.leftButton = convertView.findViewById(R.id.task_item_left_button);
				holder.iconOnOff = (CheckBox)convertView.findViewById(R.id.task_icon_onoff);
				holder.barOnOff = (ImageView)convertView.findViewById(R.id.task_bar_onoff);
				convertView.setTag(holder);				
			} else {
				holder = (ViewHolder)convertView.getTag();
			}
			
			final CheckBox iconOnOff = holder.iconOnOff;
			final ImageView barOnOff = holder.barOnOff; 
			
			holder.leftButton.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					iconOnOff.toggle();
					boolean enabled = iconOnOff.isChecked();
					barOnOff.setImageResource(enabled?
							R.drawable.task_bar_on:R.drawable.task_bar_off);
					//更新task,设置
					task.setEnabled(enabled?Task.ENABLED:Task.DISABLED);
					TaskHelper.updateTask(ListActivity.this, task);
				}			
			});
			
			//设置任务启用/禁用按钮
			holder.iconOnOff = 
				(CheckBox)convertView.findViewById(R.id.task_icon_onoff);
			holder.iconOnOff.setChecked(task.isEnabled());
			
			//设置icon
			holder.barOnOff = 
				(ImageView)convertView.findViewById(R.id.task_bar_onoff);
			holder.barOnOff.setImageResource(task.isEnabled()?
					R.drawable.task_bar_on:R.drawable.task_bar_off);
			
			//Task标题
			holder.title.setText(task.getTitle());
			//Task描述
			holder.summary.setText(task.getDescription());			
			return convertView;
		}
		
		class ViewHolder {
			TextView title;		//任务标题
			TextView summary;	//任务描述
			View leftButton;    //左边的按钮
			CheckBox iconOnOff; //任务图标
			ImageView barOnOff; //图标下面的小横道
		}
		
		@Override
		public int getCount() {	
			return TaskHelper.getAllCronTask(ListActivity.this).size();}

		@Override
		public Object getItem(int position) {
			return TaskHelper.getAllCronTask(ListActivity.this).get(position);}

		@Override
		public long getItemId(int position) {
			return TaskHelper.getAllCronTask(ListActivity.this).get(position).getId();}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(Consts.TAG, "ListActivity destory");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(Consts.TAG, "ListActivity pause");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.d(Consts.TAG, "ListActivity restart");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(Consts.TAG, "ListActivity resume");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(Consts.TAG, "ListActivity stop");
	}
}